package com.briup.day41;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class ChatClient3 {
	
	public static void main(String[] args) {
		System.out.println("Welcome to 523 Chatroom!");
		String ip = "localhost";
		int port = 8888;
		Scanner sc = new Scanner(System.in);
		System.out.println("请给自己请个名称吧!");
		String nickName = sc.nextLine();
		try {
			// 创建客户端套接字对象
			// 注意：这里的ip实际上定义的是服务器的IP地址
			Socket socket = new Socket(ip, port);
			System.out.println("连接服务器成功！");
			// 向服务器发送一条信息
			PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
			// 接收服务器回复的信息
			BufferedReader br = new BufferedReader(
					new InputStreamReader(socket.getInputStream()));
	
			
			/*while (true) {
				pw.println(sc.nextLine());
				System.out.println("【服务器说】" + br.readLine());
			}	*/
			
			Thread t1 = new Thread() {
				@Override
				public void run() {
					while (true) {
						try {
							System.out.println(br.readLine());
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}	
				}
			};
			
			Thread t2 = new Thread() {
				@Override
				public void run() {
					while (true) {
						pw.println("["+nickName+"]"+sc.nextLine());
					}	
				}
			};
			
			
			t1.start();
			t2.start();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
